All files / src/app/api/admin/monitoring/traces/[id] route.ts

0% Statements 0/169
100% Branches 0/0
0% Functions 0/1
0% Lines 0/169

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170                                                                                                                                                                                                                                                                                                                                                   
/**
 * Trace Detail API
 *
 * GET /api/admin/monitoring/traces/[id]
 * Returns a single trace with all its spans.
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { logger } from '@/lib/logging';

interface RouteParams {
  params: Promise<{ id: string }>;
}

export async function GET(request: NextRequest, { params }: RouteParams) {
  try {
    const { id } = await params;

    // Get trace with all spans
    const trace = await prisma.trace.findUnique({
      where: { id },
      include: {
        spans: {
          orderBy: { startTime: 'asc' },
        },
      },
    });

    if (!trace) {
      return NextResponse.json(
        { error: 'Trace not found' },
        { status: 404 }
      );
    }

    // Build span tree for waterfall visualization
    const spanMap = new Map(trace.spans.map((s) => [s.id, s]));
    const rootSpans: typeof trace.spans = [];
    const childMap = new Map<string, typeof trace.spans>();

    for (const span of trace.spans) {
      if (!span.parentId || !spanMap.has(span.parentId)) {
        rootSpans.push(span);
      } else {
        if (!childMap.has(span.parentId)) {
          childMap.set(span.parentId, []);
        }
        childMap.get(span.parentId)!.push(span);
      }
    }

    // Build hierarchical span structure
    interface SpanNode {
      id: string;
      parentId: string | null;
      name: string;
      kind: string;
      startTime: string;
      endTime: string;
      duration: number;
      status: string;
      attributes: unknown;
      events: unknown;
      children: SpanNode[];
      // Calculated fields for waterfall
      relativeStart: number; // ms from trace start
      depth: number;
    }

    type SpanType = (typeof trace.spans)[number];
    const traceStartTime = trace.startTime.getTime();

    function buildSpanTree(span: SpanType, depth: number): SpanNode {
      const children = childMap.get(span.id) || [];
      return {
        id: span.id,
        parentId: span.parentId,
        name: span.name,
        kind: span.kind,
        startTime: span.startTime.toISOString(),
        endTime: span.endTime.toISOString(),
        duration: span.duration,
        status: span.status,
        attributes: span.attributes,
        events: span.events,
        relativeStart: span.startTime.getTime() - traceStartTime,
        depth,
        children: children
          .sort((a, b) => a.startTime.getTime() - b.startTime.getTime())
          .map((c) => buildSpanTree(c, depth + 1)),
      };
    }

    const spanTree = rootSpans
      .sort((a, b) => a.startTime.getTime() - b.startTime.getTime())
      .map((s) => buildSpanTree(s, 0));

    // Flatten tree for timeline view (depth-first)
    const flatSpans: SpanNode[] = [];
    function flattenTree(nodes: SpanNode[]): void {
      for (const node of nodes) {
        flatSpans.push(node);
        flattenTree(node.children);
      }
    }
    flattenTree(spanTree);

    // Calculate statistics
    const errorSpans = trace.spans.filter((s) => s.status === 'error');
    const dbSpans = trace.spans.filter((s) => s.name.startsWith('db.'));
    const httpSpans = trace.spans.filter((s) => s.name.startsWith('HTTP'));

    const stats = {
      totalSpans: trace.spans.length,
      errorCount: errorSpans.length,
      dbSpanCount: dbSpans.length,
      httpSpanCount: httpSpans.length,
      avgSpanDuration: Math.round(
        trace.spans.reduce((sum, s) => sum + s.duration, 0) / trace.spans.length
      ),
      maxSpanDuration: Math.max(...trace.spans.map((s) => s.duration)),
      dbTime: dbSpans.reduce((sum, s) => sum + s.duration, 0),
      httpTime: httpSpans.reduce((sum, s) => sum + s.duration, 0),
    };

    return NextResponse.json({
      trace: {
        id: trace.id,
        name: trace.name,
        serviceName: trace.serviceName,
        startTime: trace.startTime.toISOString(),
        endTime: trace.endTime.toISOString(),
        duration: trace.duration,
        status: trace.status,
        userId: trace.userId,
        requestId: trace.requestId,
      },
      spanTree,
      flatSpans,
      stats,
    });
  } catch (error) {
    logger.error('Trace detail API error', error instanceof Error ? error : new Error(String(error)), { category: 'API', traceId: (await params).id });
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

// DELETE - Delete a specific trace
export async function DELETE(request: NextRequest, { params }: RouteParams) {
  try {
    const { id } = await params;

    await prisma.trace.delete({
      where: { id },
    });

    return NextResponse.json({ status: 'deleted' });
  } catch (error) {
    logger.error('Trace delete API error', error instanceof Error ? error : new Error(String(error)), { category: 'API', traceId: (await params).id });
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}